package cn.maxwell.exception;

import cn.maxwell.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
@Component
@Slf4j
public class GlobalException {

    @ExceptionHandler(Exception.class)
    public JsonResult ExceptionHandler(Exception e){
        log.info("捕捉了Exception异常:"+e.getMessage());
        return JsonResult.error(e.getMessage());
    }

    /**
     * 自定义异常捕捉类（有错误信息和异常码）
     * @param e
     * @return
     */
    @ExceptionHandler(GlobalCustomException.class)
    public JsonResult GlobalCustomException(GlobalCustomException e){
        log.info("捕捉了GlobalCustomException异常:"+e.getErrorMessage()+"---"+e.getErrorCode());
        return JsonResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){

        //e.getBindingResult().getAllErrors().forEach(errors->{errors.getDefaultMessage();});

        //获取我们想要的错误信息返回给前端页面
        StringBuilder sbr = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(errors->{sbr.append(errors.getDefaultMessage()).append(",");});
        log.info("捕捉了MethodArgumentNotValidException异常:"+sbr.toString());
        return JsonResult.error(sbr.toString(),"10000");
    }
}
